/**
 * Description:该类主要用于创建一棵数据树
 * Copyright: 成都和为科技有限公司 2012
 * Author:zhouxingxing
 * CreateDate:2012-10-27
 * 属性：
 * 	 check - 是否支持多选 true|false 
 * 	 displayTag - 显示数据名称的标识
 *   idTag - 数据节点标识
 *   pidTag - 父数据节点标识
 *   dataSource - 数据控件
 *   params - 参数
 *   async - 异步加载, 默认false, 服务器配置要支持idKey查询，要返回子节点数量count
 *   syncdata - 同步加载数据. 默认为false
 *   load - 是否初始化加载。 默认为true
 *   chkboxtype 父节点和子节点勾选是否关联，默认是关联
 * 事件:
 * 	 onInit - 树加载完成，初始化数据前调用
 * 	 onInitParam - 在加载数据前.初始化参数.
 * 	 onInitData - 初始化加载数据调用
 *   beforeLoad - 树的数据查询之前,用于更改查询条件.
 *   onLoad - 树的数据加载完成.
 * 	 itemSelect - 当选中一个值，调用该事件. 参数为：选择值的JSON数据
 *   itemdbselect - 双击选中值
 *   beforeExpand - 展开前回调方法
 *   afterExpand - 展开前回调方法
 * 	 beforeCheck - 复选框，选中前做认证.
 *   itemNodeCreate - 创建节点前调用
 *   addhoverdom - 添加节点上移事件
 *   removehoverdom - 删除节点上移事件，同addhoverdom为一体
 */

function Tree() {}

Tree.inherit(Control);

/**
 * 初始化方法
 */
Tree.prototype.init = function () {
	Tree.base.init.call(this);
}

/**
 * 创建HTML节点
 */
Tree.prototype.create = function () {
	this._html = document.createElement("div");
	$(this._html).addClass("ztree");
}


Tree.prototype.initLoad = function (oCallBack) {
	if (!$.fn.zTree) {
		this.loadCSSFile("/public.common/webapi/common/ztree/zTreeStyle.css");
		this.loadScriptFile("/public.common/webapi/common/ztree/jquery.ztree.all-3.5.js");
	}
    if (this.getAttribute().params) {
        var sParam = this.getAttribute().params.replaceAll("'","\"");
        var oParam = JSON.parse(sParam);
        this._queryParam = oParam;
    } else {
        this._queryParam = new Object();
    }
	this.triggerAttributeEvent("oninit");
    if (!this.getAttribute().type || this.getAttribute().type == "code") {
        if (!this.getAttribute().type) this.getAttribute().type = "code";
        this._queryParam.type = this.getAttribute().coderes;
    }
    if (!this.getAttribute().displaytag)
        this.getAttribute().displaytag = "cn";
    if (!this.getAttribute().idtag)
        this.getAttribute().idtag = "id";
    if (!this.getAttribute().pidtag)
        this.getAttribute().pidtag = "pid";
    this._treeObj = $.fn.zTree.init($(this.getHTML()),
        this.getSetting(), new Array());
    this._load = false;
    if (this.getAttribute().load == "false") return;
    this.loadData(oCallBack);
    this._result = [];
}

Tree.prototype.loadData = function(oCallBack, oParentNode) {
	this.triggerAttributeEvent("beforeload", oParentNode);
    var oRequest = new Object();
    if (this.getAttribute().async == "true") {
        oRequest.async = true;
    }
    if (this.getAttribute().type == "code") {
    	if(this.getAttribute().coderes == ""){
    		return false;
    	}
    }
    oRequest.params = this._queryParam;
    this.triggerAttributeEvent("oninitparam", oRequest, oParentNode);
    var othis = this;
    var async = true;
    if (this.getAttribute().syncdata && this.getAttribute().syncdata == "true") {
    	async = false;
    }
    this._loading = true; //正在加载树的数据
    this.getDataSource().queryData(oRequest, async, function(oResult){

        var oRecords = oResult.records;
        var oNewRecords = othis.triggerAttributeEvent("oninitdata", oRecords, oParentNode);
        if (oNewRecords) {
        	oRecords = oNewRecords;
        }
        if (othis.getAttribute().async == "true") {
            othis.addData(oParentNode, oRecords);
            othis.initAsyncData(oRecords);
//            othis._result.concat(oRecords);
            othis._result = oRecords;
        } else {
        	othis._result = oRecords;
            othis._treeObj = $.fn.zTree.init($(othis.getHTML()),
                othis.getSetting(), oRecords);
        }
        othis.triggerAttributeEvent("onload", oRecords, oParentNode);
        if (oCallBack) {
            oCallBack(othis, oRecords);
        }
        delete othis._loading;
        othis._load = true;
    });
}

/**
 * 重加载并显示树的数据
 * @param {} oCallBack
 */
Tree.prototype.reload = function(oCallBack) {
	if (this._loading) return;
	$(this._html).empty();
	this._treeObj = $.fn.zTree.init($(this.getHTML()),
        this.getSetting(), new Array());
    if (this.getAttribute().async == "true") {
    	if(this.getAttribute().params){
    		var sParam = this.getAttribute().params.replaceAll("'","\"");
    		var oParam = JSON.parse(sParam);
    		//保存默认条件
    		if (oParam[this.getAttribute().pidtag]) {
    			if (this._queryParam[this.getAttribute().pidtag]) {
    				this._queryParam[this.getAttribute().pidtag] = oParam[this.getAttribute().pidtag];
    			}
    		}
    	}else {
			delete this._queryParam[this.getAttribute().pidtag];
		}
    }
	this.loadData(oCallBack);
}

Tree.prototype.getSetting = function() {
	var othis = this;
	var setting = {
        data: {
        	key: {
				name: this.getAttribute().displaytag
			},
            simpleData: {  
                enable: true,
                idKey: this.getAttribute().idtag,
				pIdKey: this.getAttribute().pidtag
            }
        },
        callback: {},
        view: {
        	fontCss: this.getFont,
            dblClickExpand:(this.getAttribute().dblclick  == "false")?false:true,//增加双击是否显示隐藏子节点
        	nameIsHTML : true
        }
    };

	if(this.getAttribute().showicon){
		if(this.getAttribute().showicon == "false"){
			setting.view.showIcon = false;
		}else if(this.getAttribute().showicon == "true" || !this.getAttribute().showicon){
			setting.view.showIcon = true;
		}
	}
	if(this.getAttribute().showline){
		if(this.getAttribute().showline == "false"){
			setting.view.showLine = false;
		}else if(this.getAttribute().showline == "true" || !this.getAttribute().showline){
			setting.view.showLine = true;
		}
	}
    if (this.getAttribute().check == "true") {
    	setting.check = {
    		enable: true,
    		chkstyle: "checkbox"
    	}
		
		if(othis.getAttribute().chkboxtype=="false"){
			setting.check.chkboxType={ "Y": "", "N": "" };
		}
		
    	setting.callback.beforeCheck = function(treeId, treeNode) {
    		return othis.triggerAttributeEvent("beforecheck", treeId, treeNode);
    	};
    	setting.callback.onCheck = function(e, treeId, treeNode) {
    		othis.triggerAttributeEvent("itemselect", e, treeId, treeNode);
    	}
    } else {
    	setting.callback.onClick = function(e, treeId, treeNode) {
    		othis.triggerAttributeEvent("itemselect", e, treeId, treeNode);
    	};
    }
    setting.callback.onDblClick = function(e, treeId, treeNode) {
    		othis.triggerAttributeEvent("itemdbselect", e, treeId, treeNode);
    	};
    setting.callback.onNodeCreated = function(e, treeId, treeNode) {
    	othis.triggerAttributeEvent("itemnodecreate", e, treeId, treeNode);
    };
	setting.callback.onRename = function (e, treeId, treeNode, isCancel) {
		othis.triggerAttributeEvent("itemafterreame", e, treeId, treeNode,isCancel);
	};

	setting.view.addDiyDom = function(treeId, treeNode) {
    	othis.triggerAttributeEvent("adddiydom", treeId, treeNode);
    };
    setting.view.addHoverDom = function(treeId, treeNode) {
    	othis.triggerAttributeEvent("addhoverdom", treeId, treeNode);
    };
    setting.view.removeHoverDom = function(treeId, treeNode) {
    	othis.triggerAttributeEvent("removehoverdom", treeId, treeNode);
    };
    setting.callback.onExpand = function(e, treeId, treeNode) {
    	othis.triggerAttributeEvent("beforeexpand", e, treeId, treeNode);
    	if (!treeNode.children) treeNode.children = [];
		//异步并且不存在数据，则加载数据
		if (othis.getAttribute().async == "true"
			&& treeNode.children.length == 0) {
			var id = treeNode[othis.getAttribute().idtag];
            othis._queryParam[othis.getAttribute().pidtag] = id;
            oParentNode = othis._treeObj.getNodeByParam(othis.getAttribute().idtag, id, null);
			othis.loadData(function (oTree,oRecords) {
				othis.triggerAttributeEvent("afterexpand", othis, treeId, treeNode);
			}, oParentNode);
		}
	}
    return setting;
}

/**
 * 设置文字样式
 */
Tree.prototype.getFont = function(treeId, node) {
	return node.font ? node.font : {};
}

Tree.prototype.addData = function(oParentNode, oData) {
	return this._treeObj.addNodes(oParentNode, oData, true);
}

Tree.prototype.initAsyncData = function(oData) {
	var idKey = this.getAttribute().idtag;
	for (var i = 0 ; i < oData.length; i++) {
		var pid = oData[i][idKey];
        oParentNode = this._treeObj.getNodeByParam(idKey, pid, null);
        if (oData[i].lower == "true")
            this.addData(oParentNode, new Array());
	}
}

/**
 * 设置树标题
 * @param {Object} title
 */
Tree.prototype.setTitle = function(title){
	this._title = title;
}

/**
 * 设置选中
 * @param {} id
 */
Tree.prototype.selectNode = function(id) {
	var node = this._treeObj.getNodeByParam("id", id);
	if (node) {
		this._treeObj.selectNode(node);
		this.triggerAttributeEvent("itemselect", null, null, node);
	}
}

/**
 * 设置选中
 * @param {} ids id数组
 */
Tree.prototype.setChecks = function(ids, checked) {
	for (var i = 0 ; i < ids.length ; i++) {
		this.setCheck(ids[i], checked);
	}
}

/**
 * 
 * @param {} id
 * @param {} checked 设置选中或未选中， 默认为true
 */
Tree.prototype.setCheck = function(id, checked) {
	var node = this.getNodeById(id);
	if (typeof(checked) == "undefined") {
		checked = true;
	}
	if (node) {
		this._treeObj.checkNode(node, checked, true, true);
	}
}

Tree.prototype.checkAllNodes = function(checked) {
	this._treeObj.checkAllNodes(checked);
}

/**
 * 获得所有节点
 * @return {}
 */
Tree.prototype.getNodes = function() {
	return this._treeObj.getNodes();
}

/**
 * 通过节点id获得节点
 * @param {} id
 * @return {}
 */
Tree.prototype.getNodeById = function(id) {
	return this._treeObj.getNodeByParam(this.getAttribute().idtag, id, null);
}

/**
 * 通过参数获得节点
 * @param {} tag 标识
 * @param {} value 值
 */
Tree.prototype.getNodeByParam = function(tag, value) {
	return this._treeObj.getNodeByParam(tag, value, null);
}
/**
 * 通过参数获得节点
 * @param {} tag 标识
 * @param {} value 值
 * return type : Array
 */
Tree.prototype.getNodesByParam = function(tag, value,parentNode) {
	return this._treeObj.getNodesByParam(tag, value, parentNode);
}

Tree.prototype.removeNode = function(node, callbackFlag) {
	if(!callbackFlag) callbackFlag = false;
	return this._treeObj.removeNode(node, callbackFlag);
}

Tree.prototype.editName = function(node) {
	return this._treeObj.editName(node);
}

/**
 * 展开或隐藏树节点
 * @param {} node 树节点
 * @param {} expandFlag 展开或隐藏. 展开true, 隐藏false. 默认根据对此节点的展开状态进行 toggle 切换
 * @param {} sonSign 是否展开子孙节点. 展开true. 默认false
 * @param {} callbackFlag callbackFlag = true 表示执行此方法时触发 beforeExpand/onExpand 或 beforeCollapse/onCollapse 事件回调函数
						  callbackFlag = false 表示执行此方法时不触发事件回调函数
						  省略此参数，等同于 false
 */
Tree.prototype.expandNode = function(node, expandFlag, sonSign, callbackFlag,focus) {
	if(typeof(focus)=="undefined")
		focus=true;
	return this._treeObj.expandNode(node, expandFlag, sonSign, focus, callbackFlag);
}

/**
 * 获得选中节点
 * @return {}
 */
Tree.prototype.getSelectedNodes = function() {
	return this._treeObj.getSelectedNodes();
}

/**
 * 获得选中节点。
 * @param {} flag 默认为true
 * @return {}
 */
Tree.prototype.getCheckedNodes = function(flag) {
	return this._treeObj.getCheckedNodes(flag);
}

/**
 * 获得选中节点,只返回叶子节点。
 * @param {} flag 默认为true
 * @return {}
 */
Tree.prototype.getCheckedleafNodes = function() {
	var leafNodes = [];
	var checkNodes = this._treeObj.getCheckedNodes();
	for (var i = 0; i < checkNodes.length; i ++) {
		if (checkNodes[i].lower) continue;
		leafNodes.push(checkNodes[i]);
	}
	return leafNodes;
}

/**
 * 获得选中节点 - 如果父节点选中,不返回子节点
 */
Tree.prototype.getCheckedNodesParent = function() {
	var checkNodes = this.getCheckedNodes(true);
	//获得全选的父节点
	var checkAllParent = new Object();
	var checkNodes_n = new Array(); //处理后的选中节点
	for (var i = 0 ; i < checkNodes.length ; i++) {
		var checkNode = checkNodes[i];
		if (checkNode.check_Child_State == 2) {
			checkAllParent[checkNode.tId] = checkNode;
			if (!checkAllParent[checkNode.parentTId]) {
				checkNodes_n.push(checkNode);
			}
		}
	}
	//获得选中节点,如果父节点选中。不要子节点
	for (var i = 0 ; i < checkNodes.length ; i++) {
		var checkNode = checkNodes[i];
		if (checkNode.check_Child_State != 1  //半选中状态
		 && checkNode.check_Child_State != 2) {
		 	//父节点不是全选状态
			if (!checkAllParent[checkNode.parentTId]) {
				checkNodes_n.push(checkNode);
			}
		}
	}
	return checkNodes_n;
}

/**
 * 将树设置为不可能点击
 * @param {boolean} enable  true||false
 */
Tree.prototype.setEnable = function(){
}

Tree.prototype.setDisable = function(){
}

Tree.prototype.updateNode = function (node,checkTypeFlag) {
	if(!checkTypeFlag) checkTypeFlag = true;
	this._treeObj.updateNode(node,checkTypeFlag);
}
/**
 * 获得值
 */
Tree.prototype.getValue = function(){
}

/**
 * 设置控件值，并且定位到树形结构具体项
 * @param {Object} value  控件值 - 如果是code树，只需要传递dm值，如果是org树，需要传递id值
 */
Tree.prototype.setValue = function(value){
}

Tree.prototype.getParam = function(){
    return this._queryParam;
}

Tree.prototype.setParam = function(oParam){
	this._queryParam = oParam;
}


Tree.prototype.getResult = function() {
	return this._result;
}

/**
 * 数据是否加载
 */
Tree.prototype.hasLoad = function() {
	return this._load;
}